<template>
  <div class="login-contaner">
    <!-- 导航栏 -->
    <van-nav-bar
      class="common-nav-bar"
      title="登录"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- 表单 -->
    <van-form
      ref="refForm"
      @submit="onLogin"
      @failed="onFailed"
      validate-first
      :show-error="false"
      :show-error-message="false"
    >
      <van-field
        name="mobile"
        v-model="form.mobile"
        icon-prefix="myicon"
        left-icon="shouji"
        placeholder="请输入手机号"
        clearable
        :rules="formRules.mobile"
      />
      <van-field
        name="code"
        center
        v-model="form.code"
        icon-prefix="myicon"
        left-icon="yanzhengma"
        clearable
        placeholder="请输入短信验证码"
        :rules="formRules.code"
      >
        <template #button>
          <van-count-down
            v-if="isCountDown"
            :time="1000 * 6"
            format="ss s"
            @finish="isCountDown = false"
          />
          <van-button
            v-else
            class="send-msg-btn"
            size="small"
            round
            :loading="isSendMsgBtnLoading"
            @click.prevent="onSendMsg"
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <div class="submit-wrap">
        <van-button class="submit-btn" type="info" block>登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { apiLogin, apiGetCode } from '@/api/user'
import { Toast } from 'vant'
export default {
  name: 'LoginIndex',
  data() {
    return {
      form: {
        mobile: '13911111111',
        code: '246810'
      },
      // vant 的验证规则设置
      formRules: {
        mobile: [
          { required: true, message: '未填手机号' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式不正确'
          }
        ],
        code: [
          { required: true, message: '未填验证码' },
          {
            pattern: /^\d{6}$/,
            message: '验证码必须为6位数字'
          }
        ]
      },
      isCountDown: false,
      isSendMsgBtnLoading: false
    }
  },
  methods: {
    ...mapMutations(['setUserInfo', 'removeCacheComName']),
    async onLogin() {
      Toast.loading({
        message: '登录中...',
        forbidClick: true
      })
      try {
        const { data } = await apiLogin(this.form)
        console.log(data)
        Toast.success('登录成功')
        this.setUserInfo({ user: data.data })

        // 处理缓存组件问题
        this.removeCacheComName('Layout')

        // 在 request.js 里定义了 query 参数，记录跳转前的路径，登录后继续跳转回原来的路径
        this.$router.push(this.$route.query.redirectPath || '/')
      } catch (error) {
        Toast.error('登录失败')
        console.log(error)
      }
    },
    onFailed(errInfo) {
      if (errInfo.errors.length > 0) {
        Toast({
          position: 'top',
          message: errInfo.errors[0].message
        })
      }
    },
    // 发送验证码
    async onSendMsg() {
      try {
        // 表单验证
        await this.$refs.refForm.validate('mobile')

        // 表单验证成功后 显示 loading（loading 状态下按钮不可点击） 防止用户多次点击 发送请求
        this.isSendMsgBtnLoading = true

        // 发送请求
        await apiGetCode(this.form.mobile)

        // 倒计时开始
        this.isCountDown = true
      } catch (error) {
        let message = ''
        if (error.name === 'mobile') {
          message = error.message
        } else if (error.response && error.response.status === 429) {
          message = '请求次数过多，请稍后重试'
        } else {
          message = '请求失败，请稍后重试'
        }
        Toast({
          position: 'top',
          message
        })
      }
      // 上面逻辑处理完，loading 状态结束
      this.isSendMsgBtnLoading = false
    }
  }
}
</script>

<style scoped lang="less">
.login-contaner {
  .send-msg-btn {
    width: 76px;
    height: 23px;
    background-color: #ededed;
    .van-button__text {
      font-size: 11px;
      color: #666666;
    }
  }
  .submit-wrap {
    padding: 26px 16px;
    .submit-btn {
      background-color: #6db4fb;
      border: none;
      .van-button__text {
        font-size: 15px;
      }
    }
  }
}
</style>
